package com.sunelec.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunelec.pojo.Relationship;
import com.sunelec.pojo.Users;
import com.sunelec.pojo.associateExample;
import com.sunelec.service.TwoLevelUserService;
import com.sunelec.service.UserService;
import com.sunelec.utils.IDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 吴遵明
 * @Description: 用于二级用户注册,和关联三级用户
 * @Date: Create in 2018/05/07
 * @Modified By:
 */

/*
 * 1.页面转跳：InidManage(对二三级用户查询并分页)
 * 2.新建用户：TwoLevelUserRegister(创建新用户)
 * 3.更新用户数据：updateUser(更新数据)   -----forward转跳----->   InidManage(对二三级用户查询并分页)
 */
@Controller
public class TwoLevelUserRegisterController {

    @Autowired
    private TwoLevelUserService twoLevelUserService;

    @Autowired
    private UserService userService;

    //二级账户创建
    @RequestMapping(value = "/TwoLevelUserRegister", method = RequestMethod.POST)
    public String TwoLevelUserRegister(String username, String password, HttpSession session, Model model){
        if(userService.checkData(username,1).getStatus() == 400){
            model.addAttribute("msg","用户名已占用");
            System.out.println("用户名已占用");
            return "forward:/InidManage";
        }
        String user_id = IDUtils.getId();//id
        //将用户信息写入user表
        Users users = new Users();
        users.setUserId(IDUtils.getId());
        users.setUsersname(username);
        users.setPassword(password);
        users.setType(2);
        twoLevelUserService.createUser(users);

        model.addAttribute("msg","用户创建成功");
        return "forward:/InidManage";
    }


    //进入idManage页面，并判断权限是否为1，返回所有三级用户
    //最好让前台进行判断
    //pn2是2级用户的页数，pn3是3级用户的页数，temp是2显示2级用户框，3显示3级用户框
    @RequestMapping("/InidManage")
    public String InidManage(@RequestParam(value="pn2",defaultValue="1") Integer pn2,
                             @RequestParam(value="pn3",defaultValue="1") Integer pn3,
                             @RequestParam(value="temp",defaultValue="2") Integer temp,
                             HttpSession session, Model model) {

        //查询权限为3的用户，分页
        PageHelper.startPage(pn3, 5);
        List<Users> list = twoLevelUserService.selectUsers(3);
        PageInfo<Users> page = new PageInfo<Users>(list, 3);
        model.addAttribute("user_3", page);//为权限3的用户

        //查询权限为2的用户,分页
        PageHelper.startPage(pn2, 5);
        List<Users> list2 = twoLevelUserService.selectUsers(2);
        PageInfo<Users> page2 = new PageInfo<Users>(list2, 3);
        model.addAttribute("user_2", page2);//为权限2的用户

        if(session.getAttribute("error") != null) {//如果不为空，则是updateUser传过来的
            model.addAttribute("error",session.getAttribute("error"));
            model.addAttribute("updateId",session.getAttribute("updateid"));
            session.removeAttribute("error");//赋值完后直接删除session
            session.removeAttribute("updateid");//赋值完后直接删除session
        }
        model.addAttribute("pn2",pn2);
        model.addAttribute("pn3",pn3);
        model.addAttribute("temp",temp);
        return "idManage";
    }


    //更新User数据
    @RequestMapping("/updateUser")
    public String updateUser(HttpServletRequest request,HttpSession session, Model model) {

        String id = "0";
        String username;
        String password;
        int pn2 = 1;
        int pn3 = 1;
        int temp = 2;
        try {
            id = request.getParameter("id");
            pn2 = Integer.parseInt(request.getParameter("pn2"));
            pn3 = Integer.parseInt(request.getParameter("pn3"));
            temp = Integer.parseInt(request.getParameter("temp"));
        } catch (Exception e) {
            System.out.println("页数获取失败");
        }

        try {
            username = request.getParameter("username");
            password = request.getParameter("password");
        } catch (Exception e) {//用户数据获取失败
            session.setAttribute("error","修改失败");
            session.setAttribute("updateid",id);
            return "forward:/InidManage?pn2="+pn2+"&pn3="+pn3+"&temp="+temp;
        }

        //System.out.println("id:"+id+"username:"+username+"password:"+password);
        Users users = new Users();
        users.setUserId(id);
        users.setUsersname(username);
        users.setPassword(password);
        twoLevelUserService.updateUserById(users);
        session.setAttribute("error","修改成功");
        session.setAttribute("updateid",id);

        return "forward:/InidManage?pn2="+pn2+"&pn3="+pn3+"&temp="+temp;
    }


    @RequestMapping("/AssociatedUser")
    public String AssociatedUser(String leveluser2, String[] leveluser3) {

        if(leveluser2 == null || leveluser2.equals("")) {
            return "forward:/InAssociate?state=false";
        }
        if(leveluser3 == null) {
            return "forward:/InAssociate?state=false";
        }
        List<String> l = new ArrayList<String>();

        for(String s : leveluser3) {
            l.add(s);
        }

        // 1.根据所有3级levelname获得relationship<list>;一个三级用户绝对有一个power_id
        List<Relationship> list = twoLevelUserService.selectRelationshipByLeveluser(l);
        // 2.把所有的list里的level2users设为option2
        for(Relationship r : list) {

            r.setLevel2users(leveluser2);
            twoLevelUserService.updateRelationship(r);
        }

        return "forward:/InAssociate?state=true";
    }


    @RequestMapping("/InAssociate")
    public String InAssociate(Model model, @RequestParam(value="state",defaultValue="no")String state) {
        //查询权限为3的没有被关联的用户，分页
        List<associateExample> list = new ArrayList<>();
        List<Users> listUser = twoLevelUserService.selectAssociateUser(3);
        for(Users u : listUser) {
            list.add(new associateExample(u.getUsersname(), u.getUserId()));
        }
        //查询权限为2的用户,分页
        List<associateExample> list2 = new ArrayList<>();
        List<Users> list2User = twoLevelUserService.selectAssociateUser(2);
        for(Users u : list2User) {
            list2.add(new associateExample(u.getUsersname(), u.getUserId()));
        }

        JSONObject result = new JSONObject();
        JSONArray res = new JSONArray();
        int index = 0;
        List<associateExample> li = new ArrayList<>();
        for(int i=0; true; i++) {
            if(i >= list.size()) {
                JSONArray re = new JSONArray();
                re.addAll(li);
                JSONObject r = new JSONObject();
                r.put("con",re);
                res.add(r);
                break;
            }

            li.add(list.get(i));
            index++;
            if(index == 10) {
                index=0;

                JSONArray re = new JSONArray();
                re.addAll(li);
                JSONObject r = new JSONObject();
                r.put("con",re);
                res.add(r);

                li.clear();
            }

        }

        JSONArray res2 = new JSONArray();
        int index2 = 0;
        List<associateExample> li2 = new ArrayList<>();
        for(int i=0; true; i++) {
            if(i >= list2.size()) {
                JSONArray re2 = new JSONArray();
                re2.addAll(li2);
                JSONObject r2 = new JSONObject();
                r2.put("con",re2);
                res2.add(r2);
                break;
            }

            li2.add(list2.get(i));
            index2++;
            if(index2 == 10) {
                index2=0;

                JSONArray re2 = new JSONArray();
                re2.addAll(li2);
                JSONObject r2 = new JSONObject();
                r2.put("con",re2);
                res2.add(r2);

                li2.clear();
            }

        }
        result.put("data",res2);
        result.put("data2",res);

        model.addAttribute("result",result);
        if(list.size()%10 == 0) {
            model.addAttribute("pageNum2",list.size()/10);//页数
        } else {
            model.addAttribute("pageNum2", list.size() / 10 + 1);//页数
        }
        if(list2.size()%10 == 0) {
            model.addAttribute("pageNum1",list2.size()/10);//页数
        } else {
            model.addAttribute("pageNum1", list2.size() / 10 + 1);//页数
        }
        if(state.equals("true")) {
            model.addAttribute("state","关联成功");
        } else if(state.equals("false")) {
            model.addAttribute("state","关联失败");
        }
        return "associate";
    }
}
